<template>
    <!-- 搜索区域开始 -->
    <div class="search-container">
        <div class="wrapper">
            <h1 class="logo">
                <a href="/" title="三叉戟优购">三叉戟优购</a>
            </h1>

            <!-- 搜索区域 + 导航开始 -->
            <div class="right-wrap">
                <!-- 搜索区域开始 -->
                <div class="search-wrap">
                    <div class="left-box">宝贝</div>
                    <div class="input-box">
                        <el-input v-model="queryParams.keyword" @input="inputHandler" class="search-input" type="text" placeholder="搜索宝贝" clearable/>

                        <!-- 搜索历史区域开始 -->
                        <div class="search-history-wrap" v-if="queryParams.keyword == ''">
                            <!-- 头部区域开始 -->
                            <div class="title-box">
                                <span class="title">搜索历史：</span>
                                <div class="clear-history-box" @click="userStore.clearSearchHistory()">
                                    <i class="iconfont icon-shanchu"></i>
                                    <span class="clear-history-txt">清空历史</span>
                                </div>
                            </div>
                            <!-- 头部区域结束 -->


                            <!-- 内容区域开始 -->
                            <div class="content-box">
                                <div class="content-item" v-for="(item, index) in userStore.validSearchHistoryList" :key="index">
                                    <span class="txt">{{item}}</span>
                                    <i class="iconfont icon-chengyi" @click="userStore.deleteSearchHistory(item)"></i>
                                </div>
                            </div>
                            <!-- 内容区域结束 -->
                        </div>
                        <!-- 搜索历史区域结束 -->
                    </div>
                    <div class="right-box" @click="handlerSearch">
                        <span class="search-btn">搜索</span>
                    </div>
                </div>
                <!-- 搜索区域结束 -->

                <!-- 搜索建议区域开始 -->
                <div class="search-suggest-wrap" v-if="searchResults.length > 0">
                    <ul>
                        <template v-for="(item, index) in searchResults" :key="index">
                            <li v-if="index < 10" @click="handlerSearchSuggest(item.value)">{{ item.value }}</li>
                        </template>
                    </ul>

                    <div class="bottom-box">
                        <span class="close-txt" @click="handlerCloseSearchSuggest">关闭</span>
                    </div>
                </div>
                <!-- 搜索建议区域结束 -->
            <!-- 导航区域结束 -->

            </div>
            <!-- 搜索区域 + 导航结束 -->
        </div>
    </div>

    <!-- 骨架屏区域开始 -->
    <el-skeleton animated :loading="isShowSkeleton">
        <template #template>
            <div class="goods-list-container">

                <!-- 搜索属性区域开始 -->
                <div class="search-attr-wrap wrapper">
                    <div class="search-attr-item-wrap" v-for="(item, index) in 2" :key="index">
                        <div class="left">
                            <el-skeleton-item style="width: 50px;height: 25px;" />
                            <el-skeleton-item style="width: 32px;height: 25px;margin-left: 50px;" />
                        </div>
                        <div class="right" style="padding-left: 30px;">
                            <el-skeleton-item style="width: 50px;height: 25px;margin-left: 10px;" />
                            <el-skeleton-item style="width: 50px;height: 25px;margin: 0 10px 10px 10px;"  v-for="(item, index) in 20" :key="index"/>
                        </div>
                    </div>
                </div>

                <!-- 商品区域开始 -->
                <div class="goods-wrap wrapper">
                    <div class="filter-wrap">
                        <el-skeleton-item style="width: 100px;height: 25px;" />
                        <el-skeleton-item style="width: 100px;height: 25px;margin-left: 20px;" />
                    </div>

                    <!-- 商品区域开始 -->
                    <div class="goods-list">
                        <GoodsItemSkeleton  :isShowSkeleton="isShowSkeleton" v-for="(item, index) in 5" :key="index"/>
                    </div>
                </div>

            </div>
        </template>
    </el-skeleton>
    <!-- 骨架屏区域结束 -->

    <!-- 内容区域开始 -->
    <div class="goods-list-container">
        <!-- 搜索属性区域开始 -->
        <div class="search-attr-wrap wrapper">
            <div class="search-attr-item-wrap">
                <div class="left">
                    <div class="title">品牌：</div>
                    <div class="all">全部</div>
                </div>
                <div class="right">
                    <span>三只松鼠</span>
                    <span v-for="(item, index) in 20" :key="index">百香味</span>
                </div>
            </div>
            <div class="search-attr-item-wrap">
                <div class="left">
                    <div class="title">品牌：</div>
                    <div class="all">全部</div>
                </div>
                <div class="right">
                    <span>三只松鼠</span>
                    <span v-for="(item, index) in 20" :key="index">百香味</span>
                </div>
            </div>
        </div>
        <!-- 搜索属性区域结束 -->

        <!-- 商品区域开始 -->
        <div class="goods-wrap wrapper">
            <div class="filter-wrap">
                <!-- 过滤方式 -->
                <div class="filter">
                    <el-dropdown @command="handlerFilterChange">
                        <span class="el-dropdown-link">
                        {{ selectedFilterText }}
                        <el-icon class="el-icon--right">
                            <arrow-down />
                        </el-icon>
                        </span>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item command="all">全部商品</el-dropdown-item>
                                <el-dropdown-item command="new_goods">新款商品</el-dropdown-item>
                                <el-dropdown-item command="hot_goods">热门商品</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>

                <!-- 排序方式 -->
                <div class="sort">
                    <el-dropdown @command="handlerSortChange">
                        <span class="el-dropdown-link">
                        {{selectedSortText}}
                        <el-icon class="el-icon--right">
                            <arrow-down />
                        </el-icon>
                        </span>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item :command="0">默认排序</el-dropdown-item>
                                <el-dropdown-item :command="1">价格由低到高</el-dropdown-item>
                                <el-dropdown-item :command="2">价格由高到低</el-dropdown-item>
                                <el-dropdown-item :command="3">销量排序</el-dropdown-item>
                                <el-dropdown-item :command="4">点赞排序</el-dropdown-item>
                                <el-dropdown-item :command="5">收藏排序</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>

                <!-- 综合筛选 -->
                <div class="composite-filtrate"></div>

                <!-- 价格区间 -->
                <div class="price-interval">
                    <div class="price-box">
                        <span class="txt">最低价</span>
                        <el-input v-model="minPrice" style="width: 100px" @input="priceInputHandler" clearable/>
                    </div>

                    <div class="price-box">
                        <span class="txt">最高价</span>
                        <el-input v-model="maxPrice" style="width: 100px" @input="priceInputHandler" clearable/>
                    </div>

                    <div class="price-btn" @click="handlerPriceFilter">确定</div>
                </div>
            </div>

            <!-- 列表区域开始 -->
            <div class="goods-list" v-if="goodsList.length > 0">
                <goods-item v-for="(item, index) in goodsList" :goods="item" :key="index" :tag="item.tag"></goods-item>
            </div>
            <Empty v-if="!isShowSkeleton && goodsList.length == 0"/>
            <!-- 列表区域结束 -->

            <!-- 分页区域开始 -->
            <div class="page-wrap" v-if="total > 0">
                <el-pagination 
                    background 
                    layout="prev, pager, next" 
                    :total="total"
                    :page-size="queryParams.page_size"
                    :current-page="queryParams.page"
                    @current-change="handlerCurrentChange"
                    />
            </div>
            <!-- 分页区域结束 -->
        </div>
        <!-- 商品区域结束 -->
    </div>

    <!-- 返回顶部组件 -->
    <BackTop @backTop="backTop" :isShowBackTop="isShowBackTop"></BackTop>
</template>


<script setup>
import { ref, reactive, onMounted, inject, watch } from "vue";
import { useRoute} from 'vue-router'
import { reqGetGoodsListAPI, reqSearchFilterAPI, reqSearchSuggestCompletionAPI } from "@/apis/goods"
import useScroll from '@/utils/useScroll'

import {useUserStore} from "@/stores/modules/user"

import { ElNotification } from 'element-plus'

// --------------------- 返回顶部功能开始 ---------------------
const isShowBackTop = ref(false)
const {scrollTop, scrollToTop} = useScroll()
watch(scrollTop, (oldValue, newValue) => {
    isShowBackTop.value = oldValue > 800 ? true : false
})

// 返回顶部
const backTop = () => {
    scrollToTop()
}
// --------------------- 返回顶部功能结束 ---------------------



// --------------------- 定义全局变量开始 ---------------------
// 定义路由
const route = useRoute()

// 定义延时器
const timer = ref(null)

// 定义推荐搜索列表
const searchResults = ref([])

// 定义是否显示骨架
const isShowSkeleton = ref(false)

const global = inject('global')

// 定义用户存储
const userStore = useUserStore()
// --------------------- 定义全局变量结束 ---------------------



// ----------------------- 加载页面开始 -----------------------
onMounted( async () => {
    queryParams.cid = route.query.cid != undefined ? route.query.cid : 0
	queryParams.keyword = route.query.keyword != undefined ? route.query.keyword : ''

    await Promise.all([getSearchFilter(), getGoodsList()])
})
// ----------------------- 加载页面结束 -----------------------



// --------------------- 输入事件处理开始 ---------------------
const inputHandler = () => {
	// ------------------ 防抖处理 ------------------
	// 清除延时器
	clearTimeout(timer.value)
	// 重新启动延时器
	timer.value = setTimeout(() => {
		getSearchList()
	}, 500)
}
// --------------------- 输入事件处理结束 ---------------------



// --------------------- 处理搜索建议开始 ---------------------
const handlerSearchSuggest = (value) => {
    queryParams.keyword = value
    searchResults.value = []
}
// --------------------- 处理搜索建议结束 ---------------------



// --------------------- 关闭搜索建议开始 ---------------------
const handlerCloseSearchSuggest = () => {
    searchResults.value = []
}
// --------------------- 关闭搜索建议结束 ---------------------



// ------------- 根据搜索关键词,搜索商品建议列表开始 -------------
const getSearchList = async () => {
	if (queryParams.keyword == '') {
		searchResults.value = []
		return
	}
	
	const result = await reqSearchSuggestCompletionAPI(queryParams.keyword)
	searchResults.value = result.data.search_suggests != null ? result.data.search_suggests : []
	
    // 添加搜索历史
	userStore.addSearchHistory(queryParams.keyword)
}
// ------------- 根据搜索关键词,搜索商品建议列表结束 -------------



// ---------------------- 搜索商品功能开始 ----------------------
const handlerSearch = async () => {
    await Promise.all([getSearchFilter(), getGoodsList()])
}
// ---------------------- 搜索商品功能结束 ----------------------



// ---------------------- 获取搜索属性开始 ----------------------
// 定义搜索数据
const searchFilterList = ref([])
// 获取搜索属性数据
const getSearchFilter = async () => {
    if (queryParams.keyword == '') {
        return false
    }
    const result = await reqSearchFilterAPI({...queryParams, brand_name: '', category_name: '', page_size: 10})
    searchFilterList.value = result.data.search_filters != null ? result.data.search_filters : []
}
// ----------------------- 获取搜索属性结束 -----------------------



// ----------------------- 商品过滤功能开始 -----------------------
const selectedFilterText = ref('全部商品')
const handlerFilterChange = async  (e) => {
    queryParams.is_new = "all"
    queryParams.is_hot = "all"
    if (e == "all") { // 当为all表示全部
        selectedFilterText.value = '全部商品'
    } else if (e == "new_goods") { // 新款商品
        queryParams.is_new = "1"
        selectedFilterText.value = '新款商品'
    } else if (e == "hot_goods") { // 热门商品
        queryParams.is_hot = "1"
        selectedFilterText.value = '热门商品'
    }

    queryParams.page = 1
    await getGoodsList()
}
// ----------------------- 商品过滤功能结束 -----------------------



// ----------------------- 商品排序功能开始 -----------------------
const selectedSortText = ref('默认排序')
const handlerSortChange = async  (e) => {
    switch (e) {
        case 1: // 价格由低到高
            queryParams.sort_field = 'price'
            queryParams.sort_mode = 'asc'
            selectedSortText.value = '价格由低到高'
            break;
        case 2: // 价格由高到低
            queryParams.sort_field = 'price'
            queryParams.sort_mode = 'desc'
            selectedSortText.value = '价格由高到低'
            break;
        case 3: // 销量排序
            queryParams.sort_field = 'sales_num'
            queryParams.sort_mode = 'desc'
            selectedSortText.value = '销量排序'
            break;
        case 4: // 点赞排序
            queryParams.sort_field = 'like_num'
            queryParams.sort_mode = 'desc'
            selectedSortText.value = '点赞排序'
            break;
        case 5: // 收藏排序
            queryParams.sort_field = 'collect_num'
            queryParams.sort_mode = 'desc'
            selectedSortText.value = '收藏排序'
            break;
        default:
            queryParams.sort_field = 'goods_id'
            queryParams.sort_mode = 'desc'
            selectedSortText.value = '默认排序'
            break;
    }

    queryParams.page = 1
    await getGoodsList()
}
// ----------------------- 商品排序功能结束 -----------------------



// ----------------------- 价格过滤功能开始 -----------------------
const minPrice = ref('')
const maxPrice = ref('')
const priceInputHandler = () => {
    minPrice.value = minPrice.value.replace(/[^\d]/g,'')
    queryParams.min_price = minPrice.value != '' ? minPrice.value * 100 : ''

    maxPrice.value = maxPrice.value.replace(/[^\d]/g,'')
    queryParams.max_price = maxPrice.value != '' ? maxPrice.value * 100 : ''
}

const handlerPriceFilter = async () => {
    if ((queryParams.min_price != '' && queryParams.max_price != '') && (queryParams.min_price > queryParams.max_price)) {
        ElNotification.error('最低价不能大于最高价')
        return
    }


    queryParams.page = 1
    await getGoodsList()
}
// ----------------------- 价格过滤功能开始 -----------------------



// ------------------------- 翻页功能开始 -------------------------
const handlerCurrentChange = async (page) => {
    queryParams.page = page
    await getGoodsList()

    // 返回顶部
    scrollToTop()
}
// ------------------------- 翻页功能结束 -------------------------



// --------------------- 获取商品列表功能开始 ---------------------
// 定义商品列表
const goodsList = ref([])

// 商品数量
const total = ref(0)

// 总页数
const pageTotal = ref(0)

// 请求参数
const queryParams = reactive({
	keyword: '',
    top_cid: global.CID,
	cid: 0,
	brand_id: 0,
    brand_name: '',
    category_name: '',
	min_price: '',
	max_price: '',
	sort_field: 'goods_id',
	sort_mode: 'desc',
    is_hot: 'all',
    is_new: 'all',
	page: 1,
	page_size: 20
})

// 请求商品数据
const getGoodsList = async () => {
    // 显示骨架
    if (queryParams.page == 1) {
        isShowSkeleton.value = true
    }

    goodsList.value = []

	// 请求数据
	const result = await reqGetGoodsListAPI(queryParams)
	let goodsItems = result.data.goods != null ? result.data.goods : []
    total.value = result.data.total
    pageTotal.value = result.data.page_total
    let tag = ''
    goodsItems.forEach(item => {
        if (item.is_hot == 1) {
            tag = '热门'
        }
        if (item.is_new == 1) {
            tag = '新款'
        }
        item.tag = tag
        item.sales_num = 10000
    })
    goodsList.value = goodsItems

    isShowSkeleton.value = false
}
// --------------------- 获取商品列表功能结束 ---------------------
</script>


<style scoped lang="scss">
// 搜索区域
.search-container {
    position: fixed;
    width: 100%;
    padding-top: 52px;
    background-color: #fff;
    z-index: 100;
    .wrapper {
        height: 130px;
        display: flex;
        align-items: center;
        // logo区域
        .logo {
            a {
                display: block;
                width: 180px;
                height: 80px;
                background-image: url(@/assets/images/logo.png);
                background-size: 100% 100%;
                font-size: 0;
            }
        }

        // 右边区域
        .right-wrap {
            padding-left: 100px;
            position: relative;
            // 搜索区域
            .search-wrap {
                display: flex;
                align-items: center;

                width: 750px;
                height: 48px;
                border-radius: 25px;
                overflow: hidden;
                border: 2px solid $main-color;
                .left-box {
                    padding: 8px 0;
                    width: 60px;
                    display: flex;
                    justify-content: center;
                    border-right: 1px solid #F3F0F0;
                }
                .input-box {
                    flex: 1;
                    padding-left: 6px;
                    .search-input {
                        width: 100%;
                        height: 48px;
                        border: none
                    }

                    &:hover .search-history-wrap {
                        display: block;
                    }

                    ::v-deep(.el-input .el-input__wrapper) {
                        box-shadow: none;
                    }

                    // 搜索历史区域
                    .search-history-wrap {
                        display: none;
                        position: absolute;
                        left: 162px;
                        top: 46px;
                        width: 588px;
                        border: 2px solid $main-color;
                        padding-top: 10px;
                        border-top: 0;
                        border-bottom-left-radius: 10px;
                        border-bottom-right-radius: 10px;
                        overflow: hidden;
                        background-color: #fff;
                        .title-box {
                            display: flex;
                            justify-content: space-between;
                            padding: 10px;
                            font-size: 14px;
                            color: #999;
                            .clear-history-box {
                                cursor: pointer;
                            }
                        }

                        .content-box {
                            display: flex;
                            flex-wrap: wrap;
                            padding: 10px 0;
                            font-size: 14px;
                            .content-item {
                                cursor: pointer;
                                padding: 5px 2px 5px 10px;
                                margin: 5px;
                                border: 1px solid #999;
                                border-radius: 4px;
                                .txt {
                                    padding-right: 6px;
                                    &:hover {
                                        color: $main-color;
                                    }
                                }
                                .icon-chengyi {
                                    &:hover {
                                        color: $main-color;
                                    }
                                }
                            }
                        }
                    }
                }
                .right-box {
                    width: 100px;
                    background-color: $main-color;
                    text-align: center;
                    padding: 20px 0;
                    cursor: pointer;

                    .search-btn {
                        color: #fff;
                    }
                }
            }

            // 搜索建议区域
            .search-suggest-wrap {
                position: absolute;
                left: 162px;
                top: 48px;
                width: 587px;
                background-color: #fff;
                z-index: 100;
                border: 2px solid $main-color ;
                border-top: none;
                border-bottom-left-radius: 10px;
                    border-bottom-right-radius: 10px;
                    overflow: hidden;
                ul {
                    li {
                        cursor: pointer;
                        padding: 12px 10px;
                        border-bottom: 1px solid #ccc ;
                        color: #333;

                        &:hover {
                            background-color: #FACECE;
                            color: $main-color;
                        }

                        &:last-child {
                            border-bottom: none;
                        }
                    }
                }
                .bottom-box {
                    display: flex;
                    justify-content: flex-end;
                    height: 30px;
                    line-height: 30px;
                    background-color: $main-color;
                    .close-txt {
                        font-size: 14px;
                        color: #fff;
                        cursor: pointer;
                        padding: 0 20px;
                    }
                }
            }
        }
    }
}
.goods-list-container {
    padding-top: 183px;

    // 面包屑导航区域
    .crumbs-nav-wrap {
        font-size: 18px;
        padding: 20px 0;
    }

    // 搜索属性区域
    .search-attr-wrap {
        background-color: #fff;
        padding: 30px 20px 20px 20px;
        margin-bottom: 10px;
        margin-top: 10px;
        .search-attr-item-wrap {
            display: flex;
            padding-bottom: 10px;
            .left {
                display: flex;
                .title {
                    font-size: 16px;
                    font-weight: bold;
                    width: 100px;
                }
                .all {
                    color: $main-color;
                    padding-right: 30px;
                }
            }
            .right {
                display: flex;
                flex-wrap: wrap;
                flex: 1;
                span {
                    padding: 0 10px 10px 10px;
                }
            }
        }
    }

    // 商品区域
    .goods-wrap {
        background-color: #fff;
        padding: 30px 20px 20px 20px;
        margin-bottom: 10px;
        .filter-wrap {
            display: flex;
            align-items: center;
            padding-bottom: 20px;
            border-bottom: 1px solid #ccc;
            .filter {
                margin-right: 30px;
            }

            // 价格区间
            .price-interval {
                display: flex;
                align-items: center;

                color: #606266;
                .price-box {
                    margin-left: 20px;
                    .txt {
                        margin-right: 5px;
                    }
                }

                .price-btn {
                    width: 70px;
                    height: 32px;
                    line-height: 32px;
                    border: 1px solid $main-color;
                    text-align: center;
                    color: $main-color;
                    margin-left: 10px;
                    cursor: pointer;
                    border-radius: 5px;
                }
            }
        }
        .goods-list {
            display: flex;
            flex-wrap: wrap;
        }
        .page-wrap {
            display: flex;
            justify-content: center;
            padding-top: 15px;
        }
    }
}
</style>